import { mallApi } from '/api/mall'
import { uploadFile } from '/api/file'
import { onNews } from '/store/mutations'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
Page({
  data: {
    detailTitle: '' as any,
    detailImg: [] as any[],
    detailfooter: '' as any,
    photos: [] as any[],
    content_images: [] as any[],
    cansubmit: true,
    top_text: '',
    edit: false,
  },
  onLoad() {
    const {
      data: { detailTitle, detailfooter, detailImg },
    } = this
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    const {
      data: {
        title,
        dsc,
        price,
        sroce,
        categoryId,
        user,
        brandId,
        edit,
        top_text,
        content_images,
        bottom_text,
      },
    } = lastpage
    this.setData({
      title,
      dsc,
      price,
      sroce,
      categoryId,
      user,
      brandId,
      detailTitle: edit ? top_text : detailTitle,
      detailfooter: edit ? bottom_text : detailfooter,
      detailImg: edit ? content_images : detailImg,
      edit,
    })
  },
  /** 输入标题 */
  detailTitle(e: WechatMiniprogram.CustomEvent) {
    const detailTitle = e.detail.value
    this.setData({
      detailTitle,
    })
  },
  /** 选择图片 */
  addImg() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        const detailImg = [...this.data.detailImg, res.tempFilePaths[0]]
        this.setData({
          detailImg,
        })
      },
    })
  },
  /** 取消选中图片 */
  deletImg() {
    this.setData({
      detailImg: [],
    })
  },
  /** 输入底部标题 */
  detailfooter(e: WechatMiniprogram.CustomEvent) {
    const detailfooter = e.detail.value
    this.setData({
      detailfooter,
    })
  },
  /** 上传图片 */
  async submitImg() {
    try {
      await onNews(['{{NEW_ORDER_KEY}}'])
    } catch (error) {
      wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
    }
    if (!this.data.cansubmit) return
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      cansubmit: false,
    })
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    const photos = [] as any
    let content_images = [] as any
    const {
      data: { img, videoSize },
    } = lastpage

    try {
      for (let i = 0; i < img.length; i++) {
        const item = img[i] as any
        try {
          photos.push(
            item.video
              ? item.video && item.image && !item.video.url && !item.image.url
                ? {
                    video: await uploadFile(item.video, videoSize),
                    image: await uploadFile(item.image),
                  }
                : { video: item.video.node, image: item.image.node }
              : item.image.url
              ? { image: item.image.node }
              : { image: await uploadFile(item.image) },
          )
        } catch (error) {
          this.handleError(error)
        }
      }
      // eslint-disable-next-line no-case-declarations
      const imgs = this.data.detailImg.map(async (i: any) => {
        return typeof i === 'string' ? await uploadFile(i) : i.node
      })
      content_images = await Promise.all(imgs)
      const timer = setInterval(() => {
        if (img.length === photos.length) {
          this.setData({
            photos,
            content_images,
          })
          clearInterval(timer)
          this.submit()
        }
      }, 1000)
    } catch (error) {
      this.handleError(error)
    }
  },

  handleError(error: any) {
    this.setData({
      cansubmit: true,
    })
    wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
  },
  async submit() {
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    let data = {} as any
    const {
      data: { detailTitle, detailfooter, photos, content_images },
    } = this
    const {
      data: {
        title,
        dsc,
        price,
        sroce,
        categoryId,
        user,
        marketPrice,
        buyRules,
        city,
        vipProduct,
        extra,
        vipMarketPrice,
        has_freight,
        freight,
        brandId,
        edit,
        commdityId,
        sku,
      },
    } = lastpage
    const type: any[] = []
    if (sku && sku.length > 0) {
      sku.map((i: any) => {
        i.extra = vipProduct == 0 ? i.extra * 100 : i.extra
        type.push(i.name)
      })
    }
    extra.low ? (extra.low = extra.low * 100) : ''
    extra.middle ? (extra.middle = extra.middle * 100) : ''
    data = {
      sku,
      author_id: user.id,
      category_id: categoryId,
      photos,
      title,
      intro: dsc,
      options: type,
      top_text: detailTitle,
      bottom_text: detailfooter,
      content_images,
      buy_limit_days: buyRules.week > 0 ? buyRules.week : 0,
      buy_limit_qty: buyRules.number > 0 ? buyRules.number : 0,
      order_min_qty: buyRules.start > 0 ? buyRules.start : 0,
      buying_read: dsc,
      remote_areas: city,
      has_freight,
      freight: freight * 100,
      type: vipProduct == 0 ? 'member' : 'score',
    }
    brandId > 0 && (data.brand_id = brandId)
    edit
      ? await mallApi
          .editProduct(
            vipProduct == 0
              ? {
                  ...data,
                  extra: extra,
                  market_price: vipMarketPrice * 100,
                  price: 0,
                  score: 0,
                }
              : {
                  ...data,
                  price: price * 100 || 0,
                  score: sroce ? sroce.toString().replace(/\b(0+)/gi, '') : 0,
                  market_price: marketPrice * 100,
                },
            commdityId,
          )
          .then((res) => {
            wx.hideLoading()
            wx.showToast({
              title: '修改成功',
              icon: 'success',
              duration: 1000,
            })
            setTimeout(() => {
              wx.reLaunch({
                url: `/mall/detail/detail?id=${res.id}`,
              })
            }, 1000)
          })
          .catch(({ data: { message } }) => {
            wx.hideLoading()
            wx.showToast({
              title: `${message}`,
              icon: 'none',
              duration: 1000,
            })
          })
      : await mallApi
          .creatProduct(
            vipProduct == 0
              ? {
                  ...data,
                  extra: extra,
                  market_price: vipMarketPrice * 100,
                  price: 0,
                  score: 0,
                }
              : {
                  ...data,
                  price: price * 100,
                  score: +sroce,
                  market_price: marketPrice * 100,
                },
          )
          .then((res) => {
            wx.hideLoading()
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 1000,
            })
            setTimeout(() => {
              // wx.reLaunch({
              //   url: `/mall/detail/detail?id=${res.id}`,
              // })
              wx.switchTab({ url: '/pages/feed/list/list' })
            }, 1000)
          })
          .catch(({ data: { message } }) => {
            wx.hideLoading()
            wx.showToast({
              title: `${message}`,
              icon: 'none',
              duration: 1000,
            })
          })
  },
})
